<template>
    <div class="default-main">
        <el-row v-loading="state.loading" :gutter="20">
            <el-col class="xs-mb-20" :xs="24" :sm="16">
                <el-form
                    v-if="!state.loading"
                    ref="formRef"
                    @keyup.enter="onSubmit(formRef)"
                    @submit.prevent=""
                    :model="state.form"
                    :rules="state.rules"
                    :label-position="'top'"
                    :key="state.formKey"
                >
                    <el-tabs v-model="state.activeTab" type="border-card">
                        <el-tab-pane class="config-tab-pane" name="base" label="基础配置">
                            <div class="config-form-item">
                                <FormItem label="应用名称" prop="app_name" type="string" v-model="state.form.app_name" />
                                <FormItem
                                    label="游客访问本系统"
                                    prop="tourist_switch"
                                    type="radio"
                                    v-model="state.form.tourist_switch"
                                    :data="{ content: { no: '不允许', yes: '允许' } }"
                                />
                                <FormItem
                                    label="游客发送文件"
                                    prop="tourist_file_switch"
                                    type="radio"
                                    v-model="state.form.tourist_file_switch"
                                    :data="{ content: { no: '不允许', yes: '允许' } }"
                                />
                                <FormItem
                                    label="会话对象输入状态显示"
                                    type="radio"
                                    v-model="state.form.input_status_display"
                                    :data="{ content: { no: '不显示', yes: '显示', csr: '仅客服代表显示' } }"
                                />
                                <FormItem
                                    label="新用户一句话欢迎文案"
                                    :attr="{
                                        blockHelp: '自动显示的欢迎文案，在用户首次打开会话窗口后，就不再显示了',
                                    }"
                                    prop="new_user_tip"
                                    type="string"
                                    v-model="state.form.new_user_tip"
                                />
                                <FormItem
                                    :input-attr="{
                                        editorType: 'md-v3',
                                        id: 'newUserMsg',
                                        editorId: 'newUserMsg',
                                        class: 'w100',
                                        footers: [],
                                    }"
                                    @keyup.enter.stop=""
                                    prop="new_user_msg"
                                    class="form-editor-160"
                                    label="新用户客服代表自动分配成功时的欢迎消息（所有客服默认）"
                                    type="editor"
                                    v-model="state.form.new_user_msg"
                                />
                                <FormItem
                                    label="客服分配方案"
                                    type="radio"
                                    v-model="state.form.csr_distribution"
                                    :data="{
                                        content: {
                                            manual: '手动接入',
                                            intensity: '自动按工作强度分配',
                                            ability: '自动按工作能力分配',
                                            turns: '自动轮流分配',
                                        },
                                    }"
                                />
                                <FormItem
                                    label="客服自动分配满载时手动接入"
                                    type="radio"
                                    v-model="state.form.csr_distribution_full_manual"
                                    :data="{
                                        content: {
                                            no: '关闭',
                                            yes: '开启',
                                        },
                                    }"
                                    :attr="{
                                        blockHelp: '若客服分配为自动，且所有客服接待量已满，则转为客服代表手动接入会话',
                                    }"
                                />
                                <FormItem
                                    label="轨迹清理周期"
                                    type="radio"
                                    v-model="state.form.trajectory_save"
                                    :data="{
                                        content: {
                                            0: '永不',
                                            7: '七天',
                                            30: '一个月',
                                            90: '三个月',
                                            180: '六个月',
                                        },
                                    }"
                                    :attr="{
                                        blockHelp: '超时的轨迹记录将被自动清理',
                                    }"
                                />
                            </div>
                            <el-button :loading="state.submitLoading" type="primary" @click="onSubmit(formRef)">{{ $t('Save') }}</el-button>
                        </el-tab-pane>
                        <el-tab-pane class="config-tab-pane" name="run" label="运行配置">
                            <div class="config-form-item">
                                <FormItem
                                    label="新消息通知（Notification API，仅窗口未聚焦同时在 https 下有效）"
                                    type="radio"
                                    v-model="state.form.new_message_notification"
                                    :data="{ content: { no: '关闭', user: '仅用户开启', csr: '仅客服代表开启', yes: '全部开启' } }"
                                />
                                <FormItem
                                    label="新消息铃声通知（用户初次交互后方可响铃，比如点击）"
                                    type="radio"
                                    v-model="state.form.new_message_sound"
                                    :data="{ content: { no: '关闭', yes: '开启' } }"
                                />
                                <FormItem
                                    label="新消息窗口抖动"
                                    type="radio"
                                    v-model="state.form.new_message_shake"
                                    :data="{ content: { no: '关闭', yes: '开启' } }"
                                />
                                <FormItem label="通知铃声文件" prop="ring" type="file" v-model="state.form.ring" />
                                <FormItem
                                    label="以下路径不启动客服系统（一行一个）"
                                    prop="not_start_paths"
                                    type="textarea"
                                    v-model="state.form.not_start_paths"
                                    @keyup.enter.stop=""
                                />
                                <FormItem
                                    label="站点后台启动客服系统"
                                    prop="backend_start"
                                    type="radio"
                                    v-model="state.form.backend_start"
                                    :data="{ content: { no: '不启动', csr_start: '为客服代表启动', yes: '总是启动' } }"
                                    :attr="{
                                        blockHelp: '可用于关闭后台的游客弹窗',
                                    }"
                                />
                                <FormItem
                                    label="商品接口地址"
                                    type="string"
                                    v-model="state.form.goods_api"
                                    :attr="{
                                        blockHelp: '客服系统可以从自定义接口中获取商品数据，接口实现示例：/worker/kefu.Examples/goods',
                                    }"
                                />
                                <FormItem
                                    label="以下用户可以发送商品"
                                    type="checkbox"
                                    v-model="state.form.send_goods_identity"
                                    :data="{ content: { tourist: '游客', csr: '客服代表', user: '普通登录用户' } }"
                                />
                                <FormItem
                                    label="订单接口地址"
                                    type="string"
                                    v-model="state.form.orders_api"
                                    :attr="{
                                        blockHelp: '客服系统可以从自定义接口中获取订单数据，接口实现示例：/worker/kefu.Examples/orders',
                                    }"
                                />
                                <FormItem
                                    label="以下用户可以发送订单"
                                    type="checkbox"
                                    v-model="state.form.send_orders_identity"
                                    :data="{ content: { tourist: '游客', csr: '客服代表', user: '普通登录用户' } }"
                                />
                            </div>
                            <el-button :loading="state.submitLoading" type="primary" @click="onSubmit(formRef)">{{ $t('Save') }}</el-button>
                        </el-tab-pane>
                        <el-tab-pane class="config-tab-pane" name="window" label="会话窗口">
                            <div class="config-form-item window-form">
                                <FormItem
                                    label="点击悬浮按钮时"
                                    type="select"
                                    v-model="state.form.click_button_mode"
                                    :data="{
                                        content: {
                                            dialog_and_small_window: '页内弹出会话窗口（若可用）+ 新的会话小窗打开会话链接',
                                            dialog_and_new_window: '页内弹出会话窗口（若可用）+ 新的标签页打开会话链接',
                                            small_window: '总是使用新的会话小窗打开会话链接',
                                            new_window: '总是使用新的标签页打开会话链接',
                                        },
                                    }"
                                />
                                <FormItem
                                    label="会话链接（开发模式）"
                                    :attr="{
                                        blockHelp: '默认的可用值为 http://localhost:1818/#/kefu 您可以根据实际情况修改',
                                    }"
                                    type="string"
                                    v-model="state.form.session_link_dev"
                                />
                                <FormItem
                                    label="会话链接（线上模式）"
                                    :attr="{
                                        blockHelp:
                                            '请填写 http[s]://前端线上部署的域名/#/kefu 正确的填写才可以确保外站或 Nuxt 工程中能够打开会话窗口',
                                    }"
                                    type="string"
                                    v-model="state.form.session_link_prod"
                                />
                                <FormItem
                                    label="轮播广告图片"
                                    :attr="{
                                        blockHelp: '建议大小：220px*150px',
                                    }"
                                    prop="sliders"
                                    type="images"
                                    v-model="state.form.sliders"
                                />
                                <FormItem
                                    :input-attr="{
                                        editorType: 'md-v3',
                                        id: 'notice',
                                        editorId: 'notice',
                                        class: 'w100',
                                        footers: [],
                                    }"
                                    @keyup.enter.stop=""
                                    class="form-editor-160"
                                    label="公告内容"
                                    type="editor"
                                    v-model="state.form.notice"
                                />
                                <FormItem
                                    label="公告主题"
                                    type="select"
                                    v-model="state.form.notice_theme"
                                    :data="{
                                        content: {
                                            error: '红色',
                                            success: '绿色',
                                            warning: '黄色',
                                            info: '灰色',
                                        },
                                    }"
                                />
                                <FormItem
                                    :input-attr="{
                                        editorType: 'md-v3',
                                        id: 'introduces',
                                        editorId: 'introduces',
                                        class: 'w100',
                                    }"
                                    @keyup.enter.stop=""
                                    label="富文本内容"
                                    type="editor"
                                    v-model="state.form.introduces"
                                />
                            </div>
                            <el-button :loading="state.submitLoading" type="primary" @click="onSubmit(formRef)">{{ $t('Save') }}</el-button>
                        </el-tab-pane>
                        <el-tab-pane class="config-tab-pane" name="auto_invitation" label="自动邀请">
                            <div class="config-form-item">
                                <FormItem
                                    label="自动邀请开关"
                                    type="radio"
                                    v-model="state.form.auto_invitation_switch"
                                    :data="{ content: { no: '关闭', yes: '开启' } }"
                                />
                                <FormItem
                                    label="仅邀请未与客服沟通过的访客"
                                    type="radio"
                                    v-model="state.form.auto_invitation_no_session"
                                    :data="{ content: { no: '否', yes: '是' } }"
                                />
                                <FormItem
                                    label="每隔多少秒弹窗会话邀请"
                                    type="number"
                                    v-model="state.form.auto_invitation_timing"
                                    :input-attr="{
                                        valueOnClear: 0,
                                    }"
                                />
                                <FormItem
                                    label="最大自动邀请次数"
                                    :attr="{
                                        blockHelp: '在用户的单次访问中最多邀请以上次数，输入0则不限',
                                    }"
                                    type="number"
                                    v-model="state.form.auto_invitation_max"
                                    :input-attr="{
                                        valueOnClear: 0,
                                    }"
                                />
                                <FormItem
                                    label="邀请弹窗背景图"
                                    :attr="{
                                        blockHelp: '建议大小：400px*180px',
                                    }"
                                    type="image"
                                    v-model="state.form.auto_invitation_bg"
                                />
                            </div>
                            <el-button :loading="state.submitLoading" type="primary" @click="onSubmit(formRef)">{{ $t('Save') }}</el-button>
                        </el-tab-pane>
                        <el-tab-pane class="config-tab-pane" name="auto_response" label="自动回复">
                            <div class="config-form-item">
                                <FormItem
                                    label="自动回复绑定用户"
                                    type="remoteSelect"
                                    v-model="state.form.auto_response_user_id"
                                    :input-attr="{
                                        pk: 'user.id',
                                        field: 'nickname',
                                        remoteUrl: '/admin/kefu.User/index',
                                        emptyValues: ['', null, undefined, 0],
                                        valueOnClear: 0,
                                    }"
                                    :attr="{
                                        blockHelp: '请于客服系统管理->用户管理内准备一个账户（设置账户的绑定会员及昵称等）用于部分自动回复场景',
                                    }"
                                />
                                <FormItem
                                    label="知识库自动回复模式"
                                    type="select"
                                    v-model="state.form.kbs_auto_response_mode"
                                    :key="state.form.kbs_auto_response_mode"
                                    :data="{
                                        content: {
                                            close: '关闭知识库自动回复',
                                            csr_close: '在客服代表接入后关闭知识库自动回复',
                                            csr_auto_response_user: '在客服代表接入后以「自动回复绑定用户」自动回复知识点',
                                            csr_auto_response_csr: '在客服代表接入后以「客服代表身份」自动回复知识点',
                                        },
                                    }"
                                    :attr="{
                                        blockHelp: getKbsAutoResponseModeBlockHelp(),
                                    }"
                                />
                                <FormItem
                                    :input-attr="{
                                        editorType: 'md-v3',
                                        id: 'queuedAutoResponseContent',
                                        editorId: 'queuedAutoResponseContent',
                                        class: 'w100',
                                        footers: [],
                                    }"
                                    @keyup.enter.stop=""
                                    class="form-editor-160"
                                    label="访客初次进入排队状态自动回复内容"
                                    type="editor"
                                    v-model="state.form.queued_auto_response_content"
                                    :attr="{
                                        blockHelp: '访客初次发送消息进入排队状态（客服手动接入）时的自动回复内容',
                                    }"
                                />
                                <FormItem
                                    :input-attr="{
                                        editorType: 'md-v3',
                                        id: 'cannotReceptionContent',
                                        editorId: 'cannotReceptionContent',
                                        class: 'w100',
                                        footers: [],
                                    }"
                                    @keyup.enter.stop=""
                                    class="form-editor-160"
                                    label="无法接待自动回复内容（所有客服代表均不在线）"
                                    type="editor"
                                    v-model="state.form.cannot_reception_content"
                                />
                            </div>
                            <el-button :loading="state.submitLoading" type="primary" @click="onSubmit(formRef)">{{ $t('Save') }}</el-button>
                        </el-tab-pane>
                    </el-tabs>
                </el-form>
            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { uuid } from '/@/utils/random'
import FormItem from '/@/components/formItem/index.vue'
import { FormInstance } from 'element-plus'
import { index, save } from '/@/api/backend/kefu/config'
import { buildValidatorData } from '/@/utils/validate'

const state = reactive({
    loading: false,
    form: {
        app_name: '',
        tourist_switch: '',
        tourist_file_switch: '',
        backend_start: '',
        not_start_paths: '',
        ring: '',
        new_message_sound: '',
        new_message_shake: '',
        new_message_notification: '',
        notice: '',
        notice_theme: '',
        click_button_mode: '',
        session_link_dev: '',
        session_link_prod: '',
        sliders: '',
        introduces: '',
        auto_invitation_switch: '',
        auto_invitation_no_session: '',
        auto_invitation_timing: '',
        auto_invitation_max: '',
        auto_invitation_bg: '',
        input_status_display: '',
        new_user_tip: '',
        new_user_msg: '',
        csr_distribution: '',
        csr_distribution_full_manual: '',
        trajectory_save: '',
        goods_api: '',
        send_goods_identity: '',
        orders_api: '',
        send_orders_identity: '',
        auto_response_user_id: '',
        kbs_auto_response_mode: '',
        queued_auto_response_content: '',
        cannot_reception_content: '',
    },
    rules: {
        app_name: [buildValidatorData({ name: 'required', title: '应用名称' })],
        ring: [buildValidatorData({ name: 'required', title: '通知铃声' })],
    },
    formKey: uuid(),
    activeTab: 'base',
    submitLoading: false,
})

const formRef = ref<FormInstance>()

const onSubmit = (formRef?: FormInstance) => {
    if (!formRef) return
    formRef.validate((valid: boolean) => {
        if (valid) {
            state.submitLoading = true
            save(state.form)
                .then(() => {})
                .finally(() => {
                    state.submitLoading = false
                })
        }
    })
}

index().then((res) => {
    state.form = res.data.data
})

defineOptions({
    name: 'kefu/config',
})

const getKbsAutoResponseModeBlockHelp = () => {
    if (state.form.kbs_auto_response_mode == 'close') {
        return '知识库自动回复功能将保持关闭'
    } else if (state.form.kbs_auto_response_mode == 'csr_close') {
        return '在客服代表接入会话后，该会话的知识库自动回复功能将被关闭'
    } else if (state.form.kbs_auto_response_mode == 'csr_auto_response_user') {
        return '在客服代表接入会话后，该会话的知识库自动回复功能任然开启，但使用以上的自动回复绑定用户进行回复'
    } else if (state.form.kbs_auto_response_mode == 'csr_auto_response_csr') {
        return '在客服代表接入会话后，该会话的知识库自动回复功能任然开启，但使用客服代表的身份自动进行回复'
    }
    return ''
}
</script>

<style scoped lang="scss">
.el-tabs--border-card {
    border: none;
    box-shadow: var(--el-box-shadow-light);
    border-radius: var(--el-border-radius-base);
}
.el-tabs--border-card :deep(.el-tabs__header) {
    background-color: var(--ba-bg-color);
    border-bottom: none;
    border-top-left-radius: var(--el-border-radius-base);
    border-top-right-radius: var(--el-border-radius-base);
}
.el-tabs--border-card :deep(.el-tabs__item.is-active) {
    border: 1px solid transparent;
}
.el-tabs--border-card :deep(.el-tabs__nav-wrap) {
    border-top-left-radius: var(--el-border-radius-base);
    border-top-right-radius: var(--el-border-radius-base);
}
.el-card :deep(.el-card__header) {
    height: 40px;
    padding: 0;
    line-height: 40px;
    border: none;
    padding-left: 20px;
    background-color: var(--ba-bg-color);
}
.config-tab-pane {
    padding: 5px;
}
.config-tab-pane-add {
    width: 80%;
}
.form-editor-160 {
    :deep(.ba-editor) {
        .md-editor {
            height: 160px;
        }
    }
}
</style>
